package com.chromatic.competition.view.profile;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.chromatic.competition.R;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class MyWalletActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_wallet);

        // 初始化TextView
        TextView userLoginNameTextView = findViewById(R.id.userLoginNameTextView);
        TextView passwordTextView = findViewById(R.id.passwordTextView);
        TextView requestTypeTextView = findViewById(R.id.requestTypeTextView);
        TextView randomKeyTextView = findViewById(R.id.randomKeyTextView);
        TextView paramsTextView = findViewById(R.id.paramsTextView);

        // 解析XML
        try {
            // 从资源文件中获取XML内容
            String xmlString = getString(R.string.xml_content);

            // 创建DOM解析器工厂对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析XML字符串为Document对象
            Document doc = builder.parse(new InputSource(new StringReader(xmlString)));

            // 获取根元素
            Element rootElement = doc.getDocumentElement();

            // 获取子元素的值并显示到TextView中
            userLoginNameTextView.setText(getTagValue(rootElement, "userLoginName"));
            passwordTextView.setText(getTagValue(rootElement, "password"));
            requestTypeTextView.setText(getTagValue(rootElement, "requestType"));
            randomKeyTextView.setText(getTagValue(rootElement, "randomKey"));

            // 处理params节点下的item子节点
            StringBuilder paramsBuilder = new StringBuilder();
            NodeList paramsList = rootElement.getElementsByTagName("params")
                    .item(0).getChildNodes();
            for (int i = 0; i < paramsList.getLength(); i++) {
                Node itemNode = paramsList.item(i);
                if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
                    String itemValue = itemNode.getTextContent();
                    paramsBuilder.append(itemValue).append("\n");
                }
            }
            paramsTextView.setText(paramsBuilder.toString());

        } catch (Exception e) {
            Log.e("XML Parsing", "Error: " + e.getMessage());
        }
    }

    // 获取指定标签的值
    private String getTagValue(Element element, String tagName) {
        NodeList nodeList = element.getElementsByTagName(tagName).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }
}